package com.bezdelnick.forum.web.page;

import brix.tinymce.TinyMceMarkupEditorFactory;
import com.bezdelnick.forum.domain.Question;
import com.bezdelnick.forum.domain.Type;
import com.bezdelnick.forum.mail.MailFactory;
import com.bezdelnick.forum.mail.type.AbstractMail;
import com.bezdelnick.forum.service.ForumService;
import com.bezdelnick.forum.web.model.AddingQuestion;
import com.bezdelnick.forum.web.page.template.UserMainMenuTemplate;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.markup.html.form.*;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.springframework.web.util.HtmlUtils;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 21.07.12
 * Time: 18:39
 * To change this template use File | Settings | File Templates.
 */
@AuthorizeInstantiation("ROLE_USER")
public class AddQuestionPage extends UserMainMenuTemplate {
    private static final Logger LOGGER = LoggerFactory.getLogger(AddQuestionPage.class);

    @SpringBean
    @SuppressWarnings("unused")
    private ForumService forumService;

    private Question deliveryQuestion = null;

    public AddQuestionPage() {
        //
    }

    public AddQuestionPage(PageParameters pageParameters) {
        if (forumService.hasAdminAuthority() && pageParameters.get("action") != null && pageParameters.get("id") != null) {
            long id = pageParameters.get("id").toLong();

            if (forumService.getQuestionDao().getQuestionById(id) != null)
                deliveryQuestion = forumService.getQuestionDao().getQuestionById(id);
        }
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        // add menu component
        //add(new Label("menu", "This is menu"));

        // add body component
        AddQuestionForm form = new AddQuestionForm("form");
        add(form);
    }

    private class AddQuestionForm extends Form<AddingQuestion> {
        private static final long serialVersionUID = 1L;

        private String type;
        private String subtype;

        private List<String> typesList;
        private List<String> subtypesList;

        FormComponent<String> tbTitleQuestion;
        FormComponent<String> taTextQuestion;
        //        InPlaceEditComponent taTextQuestion;
        FormComponent<String> ddcTypes;
        FormComponent<String> ddcSubtypes;

        public AddQuestionForm(String id) {
            super(id);
            AddingQuestion addingQuestion = new AddingQuestion();

            if (deliveryQuestion != null) {
                addingQuestion.setTitle(deliveryQuestion.getTitle());
                //addingQuestion.setType(forumService.getTypeDao().getTypeById(deliveryQuestion.getTypeId()));
                //addingQuestion.setSubtype(forumService.getSubtypeDao().getSubtypeById(deliveryQuestion.getSubtypeId()));
                this.type = forumService.getTypeDao().getTypeById(deliveryQuestion.getTypeId()).getName();
                this.subtype = forumService.getSubtypeDao().getSubtypeById(deliveryQuestion.getSubtypeId()).getName();

                addingQuestion.setText(deliveryQuestion.getTextQuestion());
            }

            setModel(new CompoundPropertyModel<AddingQuestion>(addingQuestion));

            this.typesList = forumService.loadTypesNames();
            this.type = this.typesList.get(0);
        }

        @Override
        protected void onInitialize() {
            super.onInitialize();

            tbTitleQuestion = new TextField<String>("title").setRequired(true);
//            taTextQuestion = new TextArea<String>("text");
            taTextQuestion = new TinyMceMarkupEditorFactory().newEditor("text", new Model<String>(""));


            ddcTypes = new DropDownChoice<String>("type", new PropertyModel<String>(this, "type"), new TypesModel()) {
                @Override
                protected boolean wantOnSelectionChangedNotifications() {
                    return true;
                }

                @Override
                protected void onSelectionChanged(String newSelection) {
                    subtype = null;
                }
            };
            ddcTypes.setRequired(true);

            ddcSubtypes = new DropDownChoice<String>("subtype", new PropertyModel<String>(this, "subtype"), new SubtypesModel());
            ddcSubtypes.setRequired(true);
            ddcSubtypes.setOutputMarkupId(true);

            ddcTypes.add(new AjaxFormComponentUpdatingBehavior("onchange") {
                @Override
                protected void onUpdate(AjaxRequestTarget target) {
                    target.add(ddcSubtypes);
                }
            });

            add(tbTitleQuestion);
            add(taTextQuestion);
            add(ddcTypes);
            add(ddcSubtypes);
        }

        @Override
        protected void onSubmit() {
            AddingQuestion addingQuestion = getModelObject();

            Question question = new Question();
            question.setTitle(HtmlUtils.htmlEscape(addingQuestion.getTitle()));
            question.setTypeId(
                    forumService.getTypeDao().getTypeByName(
                            ddcTypes.getConvertedInput()
                    ).getId()
            );
            question.setSubtypeId(
                    forumService.getSubtypeDao().getSubtypeByName(
                            ddcSubtypes.getConvertedInput()
                    ).getId()
            );
            question.setTextQuestion(HtmlUtils.htmlUnescape(addingQuestion.getText()));
            question.setDatePublication(new Date());
            question.setEnabled(true);
            question.setNotificationEmail(true);
            question.setUserId(forumService.getCurrentUser().getId());

            setModelObject(new AddingQuestion());

            if (true) {
                // Send mail
                AbstractMail addQuestionMail = MailFactory.buildMailFor(Question.class);
                addQuestionMail.setSubject("Programmers forum. You have add a new question.");
                addQuestionMail.setRecipients(new String[]{
                        forumService.getCurrentUser().getEmail()
                });
                addQuestionMail.setSender("gofor.broake665@gmail.com");

                if (addQuestionMail.buildContext(question)) {
                    forumService.getMailSendManager().sendMessage(addQuestionMail);
                }

                // Write data to database
                if (forumService.hasAdminAuthority())
                    forumService.getQuestionDao().updateQuestion(question);
                else
                    forumService.getQuestionDao().insertQuestion(question);
            }

            // Redirecting to Admin page if current user is administrator
            // else redirect to Index Page
            if (forumService.hasAdminAuthority())
                redirectToInterceptPage(new ModeratorPage());
            else
                redirectToInterceptPage(new IndexPage());
        }

        private void createReachTextArea(FormComponent<String> textArea) {
            /*TinyMCESettings settings = new TinyMCESettings(TinyMCESettings.Theme.advanced);
            settings.disableButton(Button.styleselect);
            settings.disableButton(Button.hr);
            settings.disableButton(Button.removeformat);
            settings.disableButton(Button.visualaid);
            settings.disableButton(Button.sub);
            settings.disableButton(Button.sup);
            settings.disableButton(Button.charmap);

            settings.add(Button.fontselect, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
            settings.add(Button.fontsizeselect, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
            settings.add(Button.forecolor, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
            settings.add(Button.backcolor, TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);

            settings.setToolbarButtons(TinyMCESettings.Toolbar.second, null);
            settings.setToolbarButtons(TinyMCESettings.Toolbar.third, null);
            settings.setToolbarButtons(TinyMCESettings.Toolbar.fourth, null);

            settings.setToolbarAlign(TinyMCESettings.Align.left);
            settings.setToolbarLocation(TinyMCESettings.Location.top);
            settings.setStatusbarLocation(TinyMCESettings.Location.bottom);
            ImageUploadPanel imageUploadPanel = new ImageUploadPanel("uploadPanel");
            ImageUploadPlugin plugin = new ImageUploadPlugin(imageUploadPanel.getImageUploadBehavior());
            settings.add((Button) plugin.getImageUploadButton(), TinyMCESettings.Toolbar.first, TinyMCESettings.Position.after);
            add(imageUploadPanel);

            textArea.add(new TinyMceBehavior(settings));*/
        }

        private class TypesModel extends LoadableDetachableModel<List<? extends String>> {
            protected List<? extends String> load() {
                return forumService.loadTypesNames();
            }
        }

        private class SubtypesModel extends LoadableDetachableModel<List<? extends String>> {
            protected List<? extends String> load() {
                Type deliveryType = forumService.getTypeDao().getTypeByName(type);
                //type = null;
                List<String> subtypesNames = forumService.loadSubtypesNamesByTypeId(deliveryType.getId());
                return subtypesNames;
            }
        }
    }
}
